package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.Setmeal;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String phone = user.getPhone();
//        SMSUtils.sendMessage("itheima","SMS_460781105",phone,   code);
        log.info(code);
        if(phone!=null){
//        request.getSession().setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("发送验证码成功");
        }
       return R.error("验证码发送错误");
    }

    /**
     * 设置默认地址
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, Object > map,HttpServletRequest request){
        String phone = map.get("phone").toString();
        String inputCode=map.get("code").toString();
        String code = (String) redisTemplate.opsForValue().get(phone);
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,phone);
        User user = userService.getOne(lqw);
        if(user==null){
            User nUser=new User();
            nUser.setPhone(phone);
            userService.save(nUser);
        }
        if(inputCode!=null&&inputCode.equals(code)){
            User user1 = userService.getOne(lqw);
            request.getSession().setAttribute("user",user1.getId());
            redisTemplate.delete(phone);
            return R.success(user1);
        }
        return R.error("验证码错误");
    }
    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出登录成功");
    }
}
